package cn.sangyy.org.service.impl;

import cn.sangyy.basic.utils.MD5Utils;
import cn.sangyy.basic.utils.PageList;
import cn.sangyy.org.domain.Employee;
import cn.sangyy.org.mapper.EmployeeMapper;
import cn.sangyy.org.query.EmpQuery;
import cn.sangyy.org.service.IEmployeeService;
import cn.sangyy.user.domain.LoginInfo;
import cn.sangyy.user.mapper.LoginInfoMapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author SangYY
 * @date: 2023/05/16/16:07
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public List<Employee> getAllEmp() {
        return employeeMapper.getAllEmployee();
    }

    @Override
    public PageList<Employee> getPageList(EmpQuery empQuery) {
        Page<Employee> employeePage = new Page<>(empQuery.getPage(),empQuery.getRows());
        List<Employee> rows = employeeMapper.getPageList(employeePage,empQuery);
        return new PageList<>(employeePage.getTotal(),rows);
    }

    @Override
    public boolean updateById(Employee entity) {
        entity.setUpdateTime(new Date());
        Integer integer = employeeMapper.updateEmp(entity);
        return integer == 1;
    }

    @Override
    @Transactional
    public boolean insert(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setEmail(employee.getEmail());
        loginInfo.setPhone(employee.getPhone());
        loginInfo.setUsername(employee.getUsername());
        loginInfo.setDisable(1);
        loginInfo.setType(0);
        String salt = UUID.randomUUID().toString();
        String password = MD5Utils.encrypByMd5("car"+salt+"register"+employee.getPassword());
        loginInfo.setPassword(password);
        loginInfo.setSalt(salt);
        loginInfoMapper.insert(loginInfo);
        employee.setLogininfoId(loginInfo.getId());
        employee.setPassword(password);
        employee.setSalt(salt);
        insert(employee);
        return true;
    }
}
